package com.sub.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName SellTicketThread
 * @Description: TODO
 * @Author Submerge.
 * @Since 2024/1/2 11:28
 * @Version 1.0
 */
public class SellTicketThread implements Runnable {

    private static int ticketCount = 100;

    private Object object = new Object();

    private Lock lock = new ReentrantLock();

    //synchronized 同步代码块
    @Override
    public void run() {
        //卖票
        System.out.println("《年假不能停》总票数为100张，先到先得，售完为止！！！\n 窗口" + Thread.currentThread().getName() + "开始卖票:");
        while (true){
            synchronized (object) {
                if (ticketCount > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticketCount--;
                    System.out.println(Thread.currentThread().getName() + "卖了一张票，剩余" + ticketCount + "张票");
                }else {
                    System.out.println(Thread.currentThread().getName() + "没有票了");
                    break;
                }
            }
        }
    }
/* synchronized 同步方法
    @Override
    public void run() {
        //卖票
        System.out.println("《年假不能停》总票数为100张，先到先得，售完为止！！！\n 窗口" + Thread.currentThread().getName() + "开始卖票:");
        while (true){
            boolean b = sellMoreTickets();
            if (!b){
                break;
            }
        }
    }

    private synchronized boolean  sellMoreTickets() {
        // 卖票逻辑，此处省略具体实现
        if (ticketCount > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticketCount--;
            System.out.println(Thread.currentThread().getName() + "卖了一张票，剩余" + ticketCount + "张票");
            return true;
        }else {
            System.out.println(Thread.currentThread().getName() + "没有票了");
            return false;
        }
    }*/


  /*Lock锁
  @Override
    public void run() {
        //卖票
        System.out.println("《年假不能停》总票数为100张，先到先得，售完为止！！！\n 窗口" + Thread.currentThread().getName() + "开始卖票:");
        while (true) {
            lock.lock();
            if (ticketCount > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ticketCount--;
                System.out.println(Thread.currentThread().getName() + "卖了一张票，剩余" + ticketCount + "张票");
            } else {
                System.out.println(Thread.currentThread().getName() + "没有票了");
                break;
            }
            lock.unlock();
        }
    }*/
}
